import 'package:enterprise_v6_app/app/components/common_selection/common_selection_view.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/entities/application/basic_information/co_chemicals_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_event_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/base_risk_object_entity.dart';
import 'package:get/get.dart';
import 'package:jiffy/jiffy.dart';

class AccidentRegisterController extends GetxController {
  /// 需要提交的实体类
  EmergencyEventListEntity entity = EmergencyEventListEntity();

  /// 事故类型列表
  List<GetDictAllEntity> accidentTypeList = [];

  /// 处置状态列表
  List<GetDictAllEntity> disposalStatusList = [];

  /// 选中的事故类型
  GetDictAllEntity selectAccidentType = GetDictAllEntity();

  /// 选中的处置状态
  GetDictAllEntity selectStatus = GetDictAllEntity();

  @override
  void onInit() {
    super.onInit();
    initData();
  }

  /// 初始化数据
  Future<void> initData() async {
    // 设置接警人
    entity.answerPoliceName = UserManager.getUser()!.systemUser!.nickname;
    // 设置接警时间
    entity.policeAnswerDate = Jiffy.parseFromDateTime(DateTime.now()).format(pattern: 'yyyy-MM-dd HH:mm:ss');
    // 获取事故类型字典列表
    accidentTypeList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'sglx_6Il0PlRq');
    // 获取处置状态字典列表
    disposalStatusList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'czzt_Kl6aH3Fk');
  }

  /// 事故类型选择
  void showAccidentType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '事故类型选择',
      dataList: accidentTypeList,
      isMultiple: false,
      checkedList: [selectAccidentType],
      onCallBack: (value) {
        selectAccidentType = value[0];
        entity.accidentType = selectAccidentType.getId();
        entity.accidentTypeLabel = selectAccidentType.getShowName();
        update();
      },
    );
  }

  /// 选择事故装置
  void selectObject() {
    Get.to(CommonSelectionPage<BaseRiskObjectEntity>(title: '事故装置选择'), arguments: {
      // 'queryParameters': {},
      'interfaceUrl': Interface.getObjectAllByCompanyCode,
      'searchName': 'objectName',
      'isRadio': false,
    })?.then((value) {
      //如果不为空则设置信息
      if (value != null && value is List<BaseRiskObjectEntity>) {
        entity.accidentDevice = value.map((e) => e.getId()).toList();
        entity.accidentDeviceName = value.map((e) => e.getShowName()).toList().join(',');
        update();
      }
    });
  }

  /// 选择危险化学品
  void selectChemical() {
    Get.to(CommonSelectionPage<CoChemicalsEntity>(title: '危险化学品选择', enableLoad: true), arguments: {
      'interfaceUrl': Interface.getPageChemical,
      'searchName': 'chemicalName',
      'isRadio': false,
    })?.then((value) {
      //如果不为空则设置信息
      if (value != null) {
        final List<CoChemicalsEntity> chemicalList = value as List<CoChemicalsEntity>;
        entity.chemicalTypeNameList = chemicalList.map((e) => e.chemicalsName).join(',');
        entity.chemicalType!.clear();
        entity.chemicalType!.addAll(chemicalList.map((e) => e.id!));
        update();
      }
    });
  }

  /// 事故发生时间
  void showAccidentStartDatePicker() {
    CustomSelectFunction.selectDateTime(onCallBack: (String value) {
      entity.accidentStartDate = value;
      update();
    });
  }

  ///处置状态选择
  void showDisposalStatus() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '处置状态选择',
      dataList: disposalStatusList,
      isMultiple: false,
      checkedList: [selectStatus],
      onCallBack: (value) {
        selectStatus = value[0];
        entity.handleState = selectStatus.getId();
        entity.handleStateLabel = selectStatus.getShowName();
        update();
      },
    );
  }

  /// 提交
  Future<void> submit() async {
    if (entity.accidentName!.isEmpty) {
      AppToast.showWarning('请输入事故名称!');
      return;
    }
    if (entity.callPoliceName!.isEmpty) {
      AppToast.showWarning('请输入报警人!');
      return;
    }
    if (entity.accidentAnswerType!.isEmpty) {
      AppToast.showWarning('请输入已采取措施!');
      return;
    }
    if (entity.accidentTypeLabel!.isEmpty) {
      AppToast.showWarning('请选择事故类型!');
      return;
    }
    if (entity.accidentDevice!.isEmpty) {
      AppToast.showWarning('请选择事故装置!');
      return;
    }
    if (entity.chemicalType!.isEmpty) {
      AppToast.showWarning('请选择涉及危险化学品!');
      return;
    }
    if (entity.accidentStartDate!.isEmpty) {
      AppToast.showWarning('请选择事故发生时间!');
      return;
    }
    if (entity.handleStateLabel!.isEmpty) {
      AppToast.showWarning('请选择处置状态!');
      return;
    }
    final res = await HttpUtil().generatePostRequest(Interface.addEmergency, data: entity.toJson()).execute();
    res.onSuccess((result) {
      Get.back();
      AppToast.showWarning('提交成功');
    });
    res.onError((result) {
      AppToast.showWarning('提交失败');
    });
  }
}
